package fic.storefinder.shared;

import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import fic.storefinder.shared.utils.Constants;

@SuppressWarnings("serial")
public class StoreFinderServiceExceptionXml extends StoreFinderServiceException {

	public StoreFinderServiceExceptionXml(String message, int errorCode) {
		super(message, errorCode);
		// TODO Auto-generated constructor stub
	}

	@Override
	public String getFormattedMessage() throws Exception {
		DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
		Document doc = docBuilder.newDocument();

		// create the root element and add it to the document
		Element response = doc.createElement(Constants.XML_NODE_RESPONSE);
		doc.appendChild(response);

		Element containsError = doc.createElement(Constants.XML_NODE_CONTAINS_ERROR);
		Text text = doc.createTextNode("true");
		containsError.appendChild(text);
		response.appendChild(containsError);

		Element error = doc.createElement(Constants.XML_NODE_ERROR);
		
		Element errorCode = doc.createElement(Constants.XML_NODE_ERROR);
		text = doc.createTextNode(this.getErrorCode() + "");
		errorCode.appendChild(text);
		error.appendChild(errorCode);
		
		Element errorMessage = doc.createElement(Constants.XML_NODE_ERRORCODE);
		text = doc.createTextNode(this.getMessage());
		errorMessage.appendChild(text);
		error.appendChild(errorMessage);
		
		response.appendChild(error);

		TransformerFactory transfac = TransformerFactory.newInstance();
		Transformer trans = transfac.newTransformer();
		trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
		trans.setOutputProperty(OutputKeys.INDENT, "yes");

		// create string from xml tree
		StringWriter sw = new StringWriter();
		StreamResult result = new StreamResult(sw);
		DOMSource source = new DOMSource(doc);
		trans.transform(source, result);
		String xmlString = sw.toString();

		return xmlString;
	}

}
